package com.app.service.Impl;

import cn.iocoder.yudao.framework.security.core.LoginUser;

import com.app.entity.po.HuibenBook;
import com.app.entity.po.HuibenClass;
import com.app.mapper.HuibenClassMapper;
import com.app.service.IHuibenClassService;
import com.app.vo.ClassInfoVO;
import com.app.vo.ClassDetailVO;
import com.app.vo.HomeworkInfoVO;
import com.app.vo.PunchStatsVO;
import com.app.vo.PunchItemVO;
import com.app.vo.ClassMemberVO;
import com.app.dto.CreateClassDTO;
import com.app.dto.JoinClassDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import com.app.mapper.HuibenClassMemberMapper;
import com.app.mapper.HuibenHomeworkMapper;
import com.app.mapper.HuibenHomeworkClassMapper;
import com.app.mapper.HuibenHomeworkUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.app.entity.po.HuibenClassMember;
import com.app.entity.po.HuibenHomework;

import java.util.Map;
import java.util.stream.Collectors;
import com.app.mapper.HuibenPunchBookMapper;
import com.app.mapper.HuibenBookMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.app.vo.BookVO;
import org.springframework.security.core.Authentication;
import java.util.ArrayList;
import org.springframework.util.Assert;


/**
 * 班级表 服务实现类
 *
 * @author lizi
 * @since 2025-07-29
 */
@Service
@Slf4j
public class HuibenClassServiceImpl extends ServiceImpl<HuibenClassMapper, HuibenClass> implements IHuibenClassService {

    @Autowired
    private HuibenClassMemberMapper huibenClassMemberMapper;
    
    @Autowired
    private HuibenHomeworkMapper huibenHomeworkMapper;

    @Autowired
    private HuibenPunchBookMapper huibenPunchBookMapper;

    @Autowired
    private HuibenBookMapper huibenBookMapper;

    @Autowired
    private HuibenHomeworkClassMapper huibenHomeworkClassMapper;

    @Autowired
    private HuibenHomeworkUserMapper huibenHomeworkUserMapper;




   

    /**
     * 获取用户班级列表
     * @return 班级信息列表
     */
    @Override
    public List<ClassInfoVO> getClassList() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        
        // 1. 先查询用户加入的班级成员记录，获取班级ID列表
        List<HuibenClassMember> memberList = huibenClassMemberMapper.selectByUserId(userId);
        
        // 2. 提取班级ID列表
        List<Long> classIds = memberList.stream()
            .map(HuibenClassMember::getClassId)
            .collect(Collectors.toList());
        
        // 3. 如果没有加入任何班级，返回空列表
        if (classIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 4. 根据班级ID列表查询每个班级的完整信息
        List<ClassInfoVO> result = new ArrayList<>();
        for (Long classId : classIds) {
            ClassInfoVO classInfo = baseMapper.selectClassInfoById(classId);
            if (classInfo != null) {
                // 设置用户在该班级中的角色
                HuibenClassMember member = memberList.stream()
                    .filter(m -> m.getClassId().equals(classId))
                    .findFirst()
                    .orElse(null);
                if (member != null) {
                    classInfo.setRole(member.getRole());
                }
                result.add(classInfo);
            }
        }
        
        return result;
    }

    /**
     * 获取班级详情（含打卡统计）
     * @param classId 班级ID
     * @return 班级详情VO
     */
    @Override
    public ClassDetailVO getClassDetail(Long classId) {
        ClassInfoVO classInfo = baseMapper.selectClassInfoById(classId);
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        //判断当前用户id是不是和creator_id相同，如果相同就设置role为creator
        if(userId.equals(classInfo.getCreatorId())){
            classInfo.setRole("creator");
        }else{
            classInfo.setRole("member");
        }
        ClassDetailVO detail = new ClassDetailVO();
        //复制classInfo到classDetail
        BeanUtils.copyProperties(classInfo, detail);
        //查询打卡统计
        PunchStatsVO punchStats = huibenClassMemberMapper.selectPunchStatsByClassId(classId);
        detail.setPunchStats(punchStats);
        return detail;
    }

    

    /**
     * 获取班级打卡统计
     * @param classId 班级ID
     * @return 打卡统计VO
     */
    // @Override
    // public PunchStatsVO getPunchStats(Long classId) {
    //     return huibenClassMemberMapper.selectPunchStatsByClassId(classId);
    // }

    /**
     * 获取班级打卡记录（分页）
     * @param classId 班级ID
     * @param page 页码
     * @param pageSize 每页数量
     * @return 打卡记录列表
     */
    @Override
    public List<PunchItemVO> getPunchList(Long classId, Integer page, Integer pageSize) {
        // 创建分页查询对象
        Page<PunchItemVO> pageParam = new Page<>(page, pageSize);
        
        // 查询打卡记录
        Page<PunchItemVO> punchPage = baseMapper.selectPunchList(pageParam, classId);
        List<PunchItemVO> punchList = punchPage.getRecords();
        
        // 为每个打卡记录查询关联的绘本信息
        for (PunchItemVO punchItem : punchList) {
            // 通过打卡ID查询关联的绘本ID列表
            List<Long> bookIds = huibenPunchBookMapper.selectBookIdsByPunchId(punchItem.getPunchId());
            
            // 通过绘本ID列表查询绘本详细信息
            if (!bookIds.isEmpty()) {
                List<HuibenBook> books = huibenBookMapper.selectByBookIds(bookIds);
                punchItem.setBooks(books);
            }
        }
        
        return punchList;
    }

    /**
     * 获取班级成员列表（分页）
     * @param classId 班级ID
     * @param page 页码
     * @param pageSize 每页数量
     * @return 班级成员列表
     */
    @Override
    public List<ClassMemberVO> getMemberList(Long classId, Integer page, Integer pageSize) {
        // 创建分页查询对象
        Page<ClassMemberVO> pageParam = new Page<>(page, pageSize);
        
        // 查询班级成员信息（包含用户信息）
        Page<ClassMemberVO> memberPage = baseMapper.selectMemberList(pageParam, classId);
        return memberPage.getRecords();
    }

    /**
     * 创建班级
     * @param dto 创建班级请求参数
     * @return 新班级ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createClass(CreateClassDTO dto) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        
        HuibenClass clazz = new HuibenClass();
        clazz.setClassName(dto.getClassName());
        clazz.setCreatorId(userId);
        clazz.setCreatorName(dto.getNickname());
        clazz.setMemberCount(1);
        clazz.setInviteCode(generateInviteCode());
        clazz.setCreatedAt(LocalDateTime.now());
        clazz.setUpdatedAt(LocalDateTime.now());
        clazz.setTenantId(122L); // 设置租户ID
        baseMapper.insert(clazz);
        
        HuibenClassMember member = new HuibenClassMember();
        member.setClassId(clazz.getClassId());
        member.setUserId(userId);
        member.setRole("creator");
        member.setJoinedAt(LocalDateTime.now());
        huibenClassMemberMapper.insert(member);
    }
    


    /**
     * 加入班级
     * @param inviteCode 邀请码
     * @return 加入的班级ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long joinClass(String inviteCode) {

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        Long classId = baseMapper.selectClassIdByInviteCode(inviteCode);
        Assert.notNull(classId, "邀请码无效");
        
        // 检查用户是否已经在该班级中
        HuibenClassMember existingMember = huibenClassMemberMapper.selectOne(
            new QueryWrapper<HuibenClassMember>()
                .eq("class_id", classId)
                .eq("user_id", userId)
        );
        Assert.isNull(existingMember, "您已加入该班级");
        
        HuibenClassMember member = new HuibenClassMember();
        member.setClassId(classId);
        member.setUserId(userId);
        member.setRole("member");
        member.setJoinedAt(LocalDateTime.now());
        huibenClassMemberMapper.insert(member);
        baseMapper.incrClassMemberCount(classId);
        
        // 查询该班级的所有作业ID
        List<Long> homeworkIds = huibenHomeworkClassMapper.selectHomeworkIdsByClassId(classId);
        
        // 如果班级有作业，则批量插入用户作业关联记录
        if (!homeworkIds.isEmpty()) {
            huibenHomeworkUserMapper.batchInsertHomeworkUser(homeworkIds, userId, classId, 0);
        }
        
        return classId;
    }

    /**
     * 检查是否为班级创建者
     * @param classId 班级ID
     * @return 是否为创建者
     */
    @Override
    public boolean checkIsCreator(Long classId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        Long creatorId = baseMapper.selectCreatorIdByClassId(classId);
        return userId.equals(creatorId);
    }

    /**
     * 生成邀请码（6位）
     * @return 邀请码
     */
    private String generateInviteCode() {
        // 简单生成6位邀请码，可根据实际需求优化
        return Long.toHexString(System.currentTimeMillis()).substring(0, 6).toUpperCase();
    }
}
